import { CheckCircleFilled, InfoCircleFilled, MinusCircleFilled, PlusCircleFilled } from '@ant-design/icons';
import { CSSProperties, useMemo, useState } from 'react';
import { udp, useUpdateEffect, useDraggableSort, Select, Divider, cssVar, Layout, Tabs } from '@cscec/udp-ui';
import styles from './index.less';
import React from 'react';

const iconStyle: CSSProperties = {
  display: 'flex',
  background: '#fff',
  borderRadius: 14,
  position: 'absolute',
  top: 0,
  right: 2,
  zIndex: 11,
  cursor: 'pointer',
  border: '2px solid white'
};

const sortCardStyle: CSSProperties = {
  width: '16%', zIndex: 1001, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center',
};

const sortInnerCardStyle: CSSProperties = {
  padding: 8, width: 71, height: 71, position: 'relative',
};

const menuNameStyle: CSSProperties = {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  fontSize: 28,
  width: 56,
  height: 56,
  color: '#fff',
  background: cssVar.primaryColor,
  borderRadius: 4,
  cursor: 'pointer'
};

const { accessToken } = udp.getUser();

const getMenuIcon = (menuIcon: string) => {
  if (menuIcon?.indexOf('http') === 0) {
    return menuIcon;
  }
  if (menuIcon?.indexOf('/minio-upload') === 0) {
    return udp.getHttpUrl(`/minio/${menuIcon}`)
  }
  const url = `/udp-file/doc/file/preview?fileId=${menuIcon}&User-Token=${accessToken}&t=${new Date().getTime()}`
  return udp.getHttpUrl(url);
}

const getIcon = (menuIcon: string, menuName: string) => {
  if (!menuIcon && menuName) {
    return <div style={menuNameStyle}>{menuName[0]}</div>;
  }
  return <img style={{ width: 56, height: 56 }} src={getMenuIcon(menuIcon)} />;
};

const CommonFunctionBox = (props: { title: any; classList: any; updateList: any, type: any; handleCheck: any; }) => {
  const {
    title, handleCheck, type, classList, updateList,
  } = props;

  const items = classList.map(each => ({
    label: each.label,
    key: each.key,
    children: (
      <div className={styles.content}>
        {(each.children || []).map((item: { id: any; menuName?: any; menuCode?: any; name?: any; menuIcon?: any; useFlg?: any; }) => (
          <CommonFunctionItem
            key={item.id}
            data={{
              ...item,
              useFlg: (updateList || []).map(e => e.menuCode).includes(item.menuCode) ? 1 : 0
            }}
            handleCheck={handleCheck}
            type={type}
          />
        ))}
      </div>
    )
  }));

  return (
    <div className={styles.box} style={{ height: 'calc(100% - 250px)' }}>
      <div className={styles.title}>{title}</div>
      <Tabs items={items} />
    </div>
  );
};
const CommonFunctionItem = ({ data, type, handleCheck }: any) => (
  <div className={styles.item}>
    <div className={styles.icon}>
      {getIcon(data.menuIcon, data.menuName || data.name)}
      <div style={iconStyle}>
        {type === 'inUse' ? (
          <MinusCircleFilled style={{ color: '#FF3141' }} onClick={() => handleCheck(data.id, 0)} />
        ) : data.useFlg ? (
          <CheckCircleFilled style={{ color: '#3BCC89' }} />
        ) : (
          <PlusCircleFilled style={{ color: '#4381FC' }} onClick={() => handleCheck(data.id, 1)} />
        )}
      </div>
    </div>
    <div className="nowrap" style={{ cursor: 'default' }}>{data.menuName || data.name}</div>
  </div>
);

export function Content({ dataRef, functionSortType }: { dataRef: any, functionSortType: number }) {
  const [sortType, setSortType] = useState(functionSortType === 0 ? 'manual_sort' : 'recent_use');
  const [list, setList] = useState<any>(dataRef.current.list);
  const [updateList, setUpdateList] = useState<any>(dataRef.current.updateList);
  const [manualList, setManualList] = useState<any>(dataRef.current.manualList);
  const [init, setInit] = useState(false); // 切换一次就不用再来回赋值了

  const [inUseList] = useMemo(() => {
    const result: any[] = [];
    (updateList || []).forEach((item: any, index: any) => {
      item.__index__ = index;
      item.useFlg = 1;
      result.push(item);
    });
    return [result];
  }, [updateList]);

  const handleCheck = (id: any, useFlg: any) => {
    // 更新上面的区域
    const item = list.find(e => e.id === id);
    let tempList = [...updateList];

    if (useFlg) {
      tempList.push(item);
    } else {
      tempList = tempList.filter(e => e.id !== id);
    }
    setUpdateList(tempList);
  };

  useUpdateEffect(() => {
    dataRef.current.updateList = updateList;
  }, [updateList]);

  /**
   * 切换的时候，直接调用保存方法，再刷新下列表
   */
  const changeSortType = (e) => {
    setSortType(e?.value);

    if (!init && e?.value === 'manual_sort') {
      let tempList = [...manualList];
      tempList.forEach(e => {
        e.useFlg = 1;
      })
      setUpdateList(tempList);
    }
    setInit(true);
  };

  return (
    <Layout autoFit style={{ overflow: 'hidden' }}>
      <div>
        <span style={{ cursor: 'default' }}>排序方式：</span>
        <Select
          defaultValue={sortType}
          id='sortType'
          style={{ minWidth: '300px' }}
          options={[
            { label: '手动排序', value: 'manual_sort' },
            { label: '最近使用', value: 'recent_use' },
          ]}
          placeholder="请选择排序方式"
          onChange={changeSortType}
        />
      </div>
      {
        sortType === 'manual_sort' ? (
          <>
            <DragBox
              title="常用功能"
              useList={inUseList}
              type="inUse"
              handleCheck={handleCheck}
              setUpdateList={setUpdateList}
            />
            <Divider />
            <CommonFunctionBox
              title='功能清单'
              classList={dataRef.current.classList}
              updateList={updateList}
              type="inGroup"
              handleCheck={handleCheck}
            />
          </>
        ) : (
          <RecentBox
            title="最近使用"
            list={dataRef.current.recentUseList}
          />
        )
      }
    </Layout>
  );
}

function DragBox(props: any) {

  const {
    title, useList, handleCheck, setUpdateList,
  } = props;
  const { SortContainer, SortElement } = useDraggableSort();
  const onSortEnd = ({ oldIndex, newIndex }: any) => {

    if (oldIndex !== newIndex) {
      setUpdateList((preArr: any) => {
        const item = preArr.splice(oldIndex, 1)[0];
        preArr.splice(newIndex, 0, item);
        return [...preArr];
      });
    }
  };

  const shouldCancelStart = (e: any) => udp.closest(e.target, (el) => el.dataset.key === 'cancel-sort');

  return (
    <div className={styles.box}>
      <div className={styles.title}>
        {title}
        <InfoCircleFilled style={{ marginLeft: 10, fontSize: 12, color: cssVar.primaryColor }} />
        <div style={{ marginLeft: 4, fontSize: 12, color: cssVar.primaryColor }}>拖拽图标进行排序</div>
      </div>
      <SortContainer axis="xy" lockAxis="xy" shouldCancelStart={shouldCancelStart} onSortEnd={onSortEnd}>
        <div className={styles.sortContainer}>
          {useList.map((item: any) => (
            <SortElement key={item.id} index={item.__index__}>
              <div style={sortCardStyle}>
                <div style={sortInnerCardStyle}>
                  {getIcon(item.menuIcon, item.menuName || item.name)}
                  <div data-key="cancel-sort" style={iconStyle} onClick={() => handleCheck(item.id, 0)}>
                    <MinusCircleFilled style={{ color: '#FF3141' }} />
                  </div>
                </div>
                <div className="nowrap" style={{ cursor: 'pointer' }}>{item.menuName || item.name}</div>
              </div>
            </SortElement>

          ))}
        </div>
      </SortContainer>
    </div>
  );
}

function RecentBox(props: any) {
  const {
    title, list,
  } = props;

  return (
    <div className={styles.box}>
      <div className={styles.title}>
        {title}
      </div>
      <div className={styles.sortContainer}>
        {list.map((item: any) => (
          <div style={sortCardStyle}>
            <div style={sortInnerCardStyle}>
              {getIcon(item.menuIcon, item.menuName || item.name)}
            </div>
            <div className="nowrap" style={{ cursor: 'pointer' }}>{item.menuName || item.name}</div>
          </div>
        ))}
      </div>
    </div>
  )
}
